var util = require('../../utils/util')
Page({
  data: {
    address: '',
  },

  // getLocation() {
  //   //获取用户地址信息
  //   wx.getLocation({
  //     success: function (res) {
  //       console.log(res)
  //     },
  //     fail: function () {
  //       wx.showToast({
  //         title: 'GPS定位失败',
  //         icon: 'none'
  //       })
  //     }
  //   })
  // },

  //分组算法
  groupBy(array, f) {
    let groups = {};
    array.forEach(function (o) {
      var group = JSON.stringify(f(o));
      groups[group] = groups[group] || [];
      groups[group].push(o);
    });
    return Object.keys(groups).map(function (group) {
      return groups[group];
    });
  },
  arrayGroupBy(list, groupId) {
    let sorted = this.groupBy(list, function (item) {
      return [item[groupId]];
    });
    return sorted;
  },
  //排序算法
  compare(propertyName) {
    return function (arr1, arr2) {
      var value1 = arr1[0][propertyName];
      var value2 = arr2[0][propertyName];
      if (value2 > value1) {
        return -1;
      } else if (value2 < value1) {
        return 1;
      } else {
        return 0;
      }
    }
  },

  //点击定位到当前城市：
  getUserLocation() {
    //判断是否已经获取到了userLocation
    if (this.data.userLocation) {
      getApp().globalData.userLocation = this.data.userLocation
      //跳转到主页
      wx.switchTab({
        url: '/pages/home/home',
      })
    } else {
      //没有则定位获取userLocation
      // 获取用户最近城市
      wx.getLocation({
        success: (res) => {
          let data = {
            latitude: res.longitude,
            altitude: res.latitude
          }
          getApp().globalData.coordinate = data
          util.sendRequest('get/recently/location', 'POST', data).then(res => {
            if (res.data.code === 0) {
              let result = res.data.result;
              //如果获取得到的城市相同，修改数据之后回到主页即可，如果不同，重新加载主页
              // let n = wx.getStorageSync('userLocation').city_name
              let n = getApp().globalData.userLocation.city_name
              // wx.setStorageSync('userLocation', result);
              getApp().globalData.userLocation = result
              this.setData({
                address: n,
                userLocation: getApp().globalData.userLocation
              })
              wx.switchTab({
                url: '/pages/home/home',
              })
            } else if (res.data.code === 10) {
              wx.showToast({
                title: res.data.msg,
              })
            }
          })
        },
        fail: function (res) {
          console.log(res)
          wx.showModal({
            title: "定位失败",
            content: 'GPS定位失败,请授权或开启GPS定位',
            confirmColor: '#ff8b9c',
            showCancel:false,
            success: (res) => {

            }
          })
        },
        complete: () => {}
      })
    }
  },

  getUserCity() {
    wx.getLocation({
      success: (res) => {
        let data = {
          latitude: res.longitude,
          altitude: res.latitude
        }
        getApp().globalData.coordinate = data
        util.sendRequest('get/recently/location', 'POST', data).then(res => {
          if (res.data.code === 0) {
            let result = res.data.result;
            let n = result.city_name
            // console.log(n)
            //将城市信息保存
            this.setData({
              address: n,
              userLocation: result
            })
          } else if (res.data.code === 10) {
            wx.showToast({
              title: res.data.msg,
            })
          }
        })
      },
      fail: function () {
        wx.showModal({
          title: "定位失败",
          content: 'GPS定位失败,请授权或开启GPS定位',
          confirmColor: '#ff8b9c',
          showCancel:false,
          success: (res) => {

          }
        })
      },
      complete: () => {}
    })
  },


  getAllCity(n = "") {
    //获取所有的城市
    let data = {
      keywords: n
    }
    util.sendRequest('get/location/city', 'GET', data).then(res => {
      // console.log(res)
      if (res.data.code === 0) {
        let result = res.data.result;
        //处理数据，将同样首字母的添加到同一个对象中，并根据首字母排序
        let CityObj = this.arrayGroupBy(result, 'city_initial');
        CityObj.sort(this.compare("city_initial"));
        // console.log(CityObj)
        this.setData({
          CityObj,
        })
      }
    })
  },

  changeAddress(e) {
    //点击列表的地址之后，提示是否修改，如果修改，则跳回到首页并重新加载
    let item = e.currentTarget.dataset.item;
    wx.showModal({
      title: '修改地址',
      content: `确定修改地址为 ${item.city_name} 吗`,
      confirmColor: '#fe5560',
      success: (res) => {
        if (res.confirm) {
          // wx.setStorageSync('userLocation', item);
          getApp().globalData.userLocation = item
          wx.reLaunch({
            url: '/pages/home/home',
          })
        }
      }
    })
    // console.log(e.currentTarget.dataset.item)
  },

  searchAddress() {

  },


  onLoad: function (options) {
    this.getAllCity();
    this.getUserCity();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})